package concurrent.aqs;

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    private final Semaphore semaphore = new Semaphore(2);

    public void doTask() {
        try {
            semaphore.acquire();
            System.out.println("Thread " + Thread.currentThread().getName() + " has acquired a permit.");
            // 模拟任务执行
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            semaphore.release();
            System.out.println("Thread " + Thread.currentThread().getName() + " has released a permit.");
        }
    }

    public static void main(String[] args) {
        SemaphoreExample example = new SemaphoreExample();
        for (int i = 0; i < 5; i++) {
            new Thread(example::doTask).start();
        }
    }
}